<template>
  <div class="page-header-index-wide">

    <a-card :bordered="false" title="我的消息">
      <a-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="massageColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
      <span slot="action" slot-scope="text, record">
        <a @click="showAnnouncement(record)">查看</a>
      </span>
      </a-table>
      <show-announcement ref="ShowAnnouncement"></show-announcement>
    </a-card>

    <a-row>
      <a-col :span="24">
        <a-card :loading="visitLoading" :bordered="false" title="用户系统访问量统计指标" :style="{ marginTop: '24px' }">
          <a-row>
            <a-col :span="6">
              <head-info title="今日IP" :content="loginfo.todayIp"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="environment" style="font-size: 24px"/>
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="今日访问" :content="loginfo.todayVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="team" style="font-size: 24px"/>
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="总访问量" :content="loginfo.totalVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="rise" style="font-size: 24px"/>
              </a-spin>
            </a-col>
          </a-row>
          <line-chart-multid :fields="visitFields" :dataSource="visitInfo"></line-chart-multid>
        </a-card>
      </a-col>
    </a-row>

    <a-skeleton active :loading="redisLoading" :paragraph="{rows: 17}">
      <a-card title="Redis监控" :style="{ marginTop: '24px' }">
        <!-- Radis 信息实时监控 -->
        <a-row :gutter="8">
          <a-col :sm="24" :xl="12">
            <area-chart-ty v-bind="memory"/>
          </a-col>
          <a-col :sm="24" :xl="12">
            <area-chart-ty v-bind="key"/>
          </a-col>
        </a-row>
      </a-card>
    </a-skeleton>

    <a-card title="磁盘使用率" :style="{ marginTop: '24px' }">
      <a-row>
        <template v-if="diskInfo && diskInfo.length>0">
          <a-col :span="8" v-for="(item,index) in diskInfo" :key=" 'diskInfo'+index ">
            <dash-chart-demo :title="item.name" :datasource="item.restPPT"></dash-chart-demo>
          </a-col>
        </template>
      </a-row>
    </a-card>

  </div>
</template>

<script>
import ChartCard from '@/components/ChartCard'
import ACol from 'ant-design-vue/es/grid/Col'
import ATooltip from 'ant-design-vue/es/tooltip/Tooltip'
import MiniArea from '@/components/chart/MiniArea'
import MiniBar from '@/components/chart/MiniBar'
import MiniProgress from '@/components/chart/MiniProgress'
import Bar from '@/components/chart/Bar'
import LineChartMultid from '@/components/chart/LineChartMultid'
import HeadInfo from '@/components/tools/HeadInfo.vue'
import Trend from '@/components/Trend'
import { getLoginfo, getVisitInfo } from '@/api/api'
import moment from 'moment'
import { getAction, putAction } from '@/api/manage'
import AreaChartTy from '@/components/chart/AreaChartTy'
import DashChartDemo from '@/components/chart/DashChartDemo'
import ARow from 'ant-design-vue/es/grid/Row'
import ShowAnnouncement from '@/components/tools/ShowAnnouncement'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'IndexDemo',
  mixins: [JeecgListMixin],
  components: {
    ATooltip,
    ACol,
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    Bar,
    Trend,
    LineChartMultid,
    HeadInfo,
    AreaChartTy,
    ARow,
    DashChartDemo,
    ShowAnnouncement,
  },
  data() {
    return {
      visitLoading: true,
      redisLoading: true,
      center: null,
      loginfo: {},
      visitFields: ['ip', 'visit'],
      visitInfo: [],
      indicator: <a-icon type="loading" style="font-size: 24px" spin/>,

      // 定时器ID
      timer: null,
      // 定时器周期
      millisec: 3000,
      // Key 实时数量
      key: {
        title: 'Radis Key 实时数量（个）',
        dataSource: [],
        y: '数量（个）',
        height: 340,
        min: 0,
        max: 100,
        color: '#FF6987',
        lineSize: 8,
        lineColor: '#DC143C'
      },
      // 内存实时占用情况
      memory: {
        title: 'Radis 内存实时占用情况（KB）',
        dataSource: [],
        y: '内存（KB）',
        min: 0,
        max: 3000,
        height: 340,
        lineSize: 8
      },
      redisInfo: [],
      columns: [{
        title: 'Key',
        align: 'center',
        dataIndex: 'key'
      }, {
        title: 'Description',
        align: 'left',
        dataIndex: 'description'
      }, {
        title: 'Value',
        align: 'center',
        dataIndex: 'value'
      }],
      diskInfo: [],
      url: {
        keysSize: '/sys/actuator/redis/keysSize',
        memoryInfo: '/sys/actuator/redis/memoryInfo',
        queryDiskInfo: 'sys/actuator/redis/queryDiskInfo',
        list: '/sys/sysAnnouncementSend/getMyAnnouncementSend',
        editCementSend: 'sys/sysAnnouncementSend/editByAnntIdAndUserId',
        readAllMsg: 'sys/sysAnnouncementSend/readAll'
      },
      path: '/dashboard/analysis',
      massageColumns: [{
        title: '标题',
        align: 'center',
        dataIndex: 'titile'
      }, {
        title: '消息类型',
        align: 'center',
        dataIndex: 'msgCategory',
        customRender: function(text) {
          if (text == '1') {
            return '通知公告'
          } else if (text == '2') {
            return '系统消息'
          } else {
            return text
          }
        }
      }, {
        title: '发布人',
        align: 'center',
        dataIndex: 'sender'
      }, {
        title: '发布时间',
        align: 'center',
        dataIndex: 'sendTime'
      }, {
        title: '优先级',
        align: 'center',
        dataIndex: 'priority',
        customRender: function(text) {
          if (text == 'L') {
            return '低'
          } else if (text == 'M') {
            return '中'
          } else if (text == 'H') {
            return '高'
          } else {
            return text
          }
        }
      }, {
        title: '状态',
        align: 'center',
        dataIndex: 'readFlag',
        customRender: function(text) {
          if (text == '0') {
            return '未读'
          } else if (text == '1') {
            return '已读'
          } else {
            return text
          }
        }
      }, {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        scopedSlots: { customRender: 'action' }
      }],
      loading: false,
      openPath: '',
      formData: '',
    }
  },
  mounted() {
    this.openTimer()
    setTimeout(() => {
      this.redisLoadData()
    }, 1000)
  },
  beforeDestroy() {
    this.closeTimer()
  },
  created() {
    setTimeout(() => {
      this.visitLoading = !this.visitLoading
    }, 1000)
    this.initLogInfo()
    getAction(this.url.queryDiskInfo).then((res) => {
      if (res.success) {
        for (var i = 0; i < res.result.length; i++) {
          res.result[i].restPPT = res.result[i].restPPT / 10
        }
        this.diskInfo = res.result
      }
    })
  },
  methods: {
    initLogInfo() {
      getLoginfo(null).then((res) => {
        if (res.success) {
          Object.keys(res.result).forEach(key => {
            res.result[key] = res.result[key] + ''
          })
          this.loginfo = res.result
        }
      })
      getVisitInfo().then(res => {
        if (res.success) {
          this.visitInfo = res.result
        }
      })
    },

    /** 开启定时器 */
    openTimer() {
      this.redisLoadData()
      this.closeTimer()
      this.timer = setInterval(() => {
        if (this.$route.path === this.path) {
          this.redisLoadData()
        }
      }, this.millisec)
    },

    /** 关闭定时器 */
    closeTimer() {
      if (this.timer) clearInterval(this.timer)
    },

    /** 查询数据 */
    redisLoadData() {
      Promise.all([
        getAction(this.url.keysSize),
        getAction(this.url.memoryInfo)
      ]).then((res) => {
        let time = moment().format('hh:mm:ss')

        let [{ dbSize: currentSize }, memoryInfo] = res
        let currentMemory = memoryInfo.used_memory / 1000

        // push 数据
        this.key.dataSource.push({ x: time, y: currentSize })
        this.memory.dataSource.push({ x: time, y: currentMemory })
        // 最大长度为6
        if (this.key.dataSource.length > 6) {
          this.key.dataSource.splice(0, 1)
          this.memory.dataSource.splice(0, 1)
        }

        // 计算 Key 最大最小值
        let keyPole = this.getMaxAndMin(this.key.dataSource, 'y')
        this.key.max = Math.floor(keyPole[0]) + 10
        this.key.min = Math.floor(keyPole[1]) - 10
        if (this.key.min < 0) this.key.min = 0

        // 计算 Memory 最大最小值
        let memoryPole = this.getMaxAndMin(this.memory.dataSource, 'y')
        this.memory.max = Math.floor(memoryPole[0]) + 100
        this.memory.min = Math.floor(memoryPole[1]) - 100
        if (this.memory.min < 0) this.memory.min = 0

      }).catch((e) => {
        console.error(e)
        this.closeTimer()
        this.$message.error('获取 Redis 信息失败')
      }).finally(() => {
        this.redisLoading = false
      })

    },

    // 获取一组数据中最大和最小的值
    getMaxAndMin(dataSource, field) {
      let maxValue = null, minValue = null
      dataSource.forEach(item => {
        let value = Number.parseInt(item[field])
        // max
        if (maxValue == null) {
          maxValue = value
        } else if (value > maxValue) {
          maxValue = value
        }
        // min
        if (minValue == null) {
          minValue = value
        } else if (value < minValue) {
          minValue = value
        }
      })
      return [maxValue, minValue]
    },
    handleDetail: function(record) {
      this.$refs.sysAnnouncementModal.detail(record)
      this.$refs.sysAnnouncementModal.title = '查看'
    },
    showAnnouncement(record) {
      putAction(this.url.editCementSend, { anntId: record.anntId }).then((res) => {
        if (res.success) {
          this.loadData()
          this.syncHeadNotic(record.anntId)
        }
      })
      if (record.openType === 'component') {
        this.openPath = record.openPage
        this.formData = { id: record.busId }
        this.$refs.showDynamNotice.detail()
      } else {
        this.$refs.ShowAnnouncement.detail(record)
      }
    },
    syncHeadNotic(anntId){
      getAction("sys/annountCement/syncNotic",{anntId:anntId})
    },
  }
}
</script>

<style lang="less" scoped>
.circle-cust {
  position: relative;
  top: 28px;
  left: -100%;
}

.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

/* 首页访问量统计 */
.head-info {
  position: relative;
  text-align: left;
  padding: 0 32px 0 0;
  min-width: 125px;

  &.center {
    text-align: center;
    padding: 0 32px;
  }

  span {
    color: rgba(0, 0, 0, .45);
    display: inline-block;
    font-size: .95rem;
    line-height: 42px;
    margin-bottom: 4px;
  }

  p {
    line-height: 42px;
    margin: 0;

    a {
      font-weight: 600;
      font-size: 1rem;
    }
  }

  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }
}
</style>